<?php

namespace App\Http\Controllers\Finance;

use Exception;
use Illuminate\Http\Request;
use App\Models\Finance\Template;
use App\Models\Finance\Condition;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\Logic\Template\StoreResource;

/**
 * 条件模板
 *
 * Date: 2018/6/8
 * @author George
 * @package App\Http\Controllers\Finance
 */
class TemplateController extends Controller
{
	/**
	 * 获取薪资条件模板
	 *
	 * Date: 2018/6/8
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(Request $request)
	{
		$this->validate($request, [
			'pattern_id' => 'required'
		]);
		$user = Auth::user();
		$query = Template::query()->select(['id', 'company_id', 'pattern_id', 'name', 'type', 'ignore'])->where([
			['company_id', '=', $user->company_id],
			['pattern_id', '=', $request->get('pattern_id')],
		]);

		return success($query->get());
	}

	/**
	 * 获取薪资条件模板详情
	 *
	 * Date: 2018/6/8
	 * @author George
	 * @param Template $template
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function show(Template $template)
	{
		$template->conditions = $template->conditions()->get();
		return success($template);
	}

	/**
	 * 创建薪资条件模板
	 *
	 * Date: 2018/6/8
	 * @author George
	 * @param StoreResource $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function store(StoreResource $request)
	{
		$attributes = $this->extractInputFromRules($request, $request->rules());
		$attributes['company_id'] = Auth::user()->company_id;
		$condition_params = array_pull($attributes, 'conditions');

		try {
			$template = Template::updateOrCreate(['id' => $request->get('id')], $attributes);
			$conditions_reuslt = [];
			foreach ($condition_params as $params) {
				$params['pattern_id'] = $attributes['pattern_id'];
				$params['template_id'] = $template->id;
				$conditions_reuslt[] = Condition::updateOrCreate(['id' => array_get($params, 'id')], $params);
			}
			$template['conditions'] = $conditions_reuslt;
			return stored($template);
		} catch (Exception $exception) {
			return internalError('保存模板信息失败');
		}
	}

	/**
	 * 删除条件模板
	 *
	 * Date: 2018/6/8
	 * @author George
	 * @param Template $template
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
	public function destroy(Template $template)
	{
		try {
			DB::beginTransaction();
			$template->delete();
			Condition::query()->where('template_id', $template->id)->delete();
			DB::commit();
			return deleted();
		} catch (Exception $exception) {
			DB::rollBack();
			return internalError('删除模板失败');
		}
	}
}
